package com.qk.management.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author: zyx
 * @created: 2025-10-04-23:22
 * @description:
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageResult<Role> page(String name, String label, Integer page, Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        List<Role> roles = roleMapper.selectByPage(name, label);
        Page<Role> pageInfo = (Page<Role>) roles;
        return new PageResult<>((int) pageInfo.getTotal(), pageInfo.getResult());
    }

    @Override
    public void addRole(Role role) {
        role.setCreateTime(LocalDateTime.now());
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.insert(role);
    }

    @Override
    public Role getById(Integer id) {
        return roleMapper.getById(id);
    }

    @Override
    public void updateRole(Role role) {
        role.setUpdateTime(LocalDateTime.now());
        roleMapper.updateRole(role);
    }

    @Override
    public void deleteRole(Integer id) {
        //查询该角色下所有用户列表，如果存在用户则不允许删除
        List<User> users = userMapper.selectList(Wrappers.<User>lambdaQuery().eq(User::getRoleId, id));
        if(!users.isEmpty()){
            CommonException.throwCommonException(ParamEnum.REFERENCE_ERROR);
        }
        roleMapper.deleteRole(id);
    }

    @Override
    public List<Role> getAllRoles() {
        List<Role> roles = roleMapper.selectAll();
        return roles;
    }
}
